"use client"

import type { Player, PlayerCategory } from "@/lib/types"
import { Trophy } from "lucide-react"
import TierBadges from "./tier-badges"
import PlayerModal from "./player-modal"
import { useState } from "react"
import ModeIcon from "./mode-icons"
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip"

interface PlayerRowProps {
  player: Player
  category: PlayerCategory
}

export default function PlayerRow({ player, category }: PlayerRowProps) {
  const [isModalOpen, setIsModalOpen] = useState(false)
  const rankColor = player.rank ? getRankColor(player.rank) : ""

  // 根据游戏模式获取对应图标
  const getModeIcon = (mode: string) => {
    switch(mode) {
      case 'SWORD':
      case 'combat':
        return <ModeIcon category="combat" size={16} />;
      case 'CRYSTAL':
      case 'crystal':
        return <ModeIcon category="crystal" size={16} />;
      case 'BUHC':
      case 'heart':
        return <ModeIcon category="heart" size={16} />;
      case 'POTION':
      case 'potion':
        return <ModeIcon category="potion" size={16} />;
      case 'NPOT':
      case 'discord':
        return <ModeIcon category="discord" size={16} />;
      case 'SMP':
      case 'circle':
        return <ModeIcon category="circle" size={16} />;
      default:
        return <Trophy className="h-4 w-4 text-yellow-500" />;
    }
  };

  // 确定应该显示的段位和模式
  const getTierDisplay = () => {
    if (category === 'overall') {
      // 不再只显示最高段位，而是收集所有非"无等级"的段位
      const allTiers = [];
      
      // 收集所有有效段位
      if (player.swordTierName && player.swordTierName !== '无等级') {
        allTiers.push({ tier: player.swordTierName, mode: 'SWORD' });
      }
      if (player.crystalTierName && player.crystalTierName !== '无等级') {
        allTiers.push({ tier: player.crystalTierName, mode: 'CRYSTAL' });
      }
      if (player.buhcTierName && player.buhcTierName !== '无等级') {
        allTiers.push({ tier: player.buhcTierName, mode: 'BUHC' });
      }
      if (player.potionTierName && player.potionTierName !== '无等级') {
        allTiers.push({ tier: player.potionTierName, mode: 'POTION' });
      }
      if (player.npotTierName && player.npotTierName !== '无等级') {
        allTiers.push({ tier: player.npotTierName, mode: 'NPOT' });
      }
      if (player.smpTierName && player.smpTierName !== '无等级') {
        allTiers.push({ tier: player.smpTierName, mode: 'SMP' });
      }
      
      // 按段位排序（高级的在前）
      allTiers.sort((a, b) => {
        const tierRank: Record<string, number> = {
          'HT1': 1, 'LT1': 2,
          'HT2': 3, 'LT2': 4,
          'HT3': 5, 'LT3': 6,
          'HT4': 7, 'LT4': 8,
          'HT5': 9, 'LT5': 10
        };
        return (tierRank[a.tier] || 99) - (tierRank[b.tier] || 99);
      });
      
      // 返回所有段位信息
      return { 
        hasTiers: allTiers.length > 0,
        allTiers 
      };
    }
    
    // 如果有明确的tier和tierMode属性，使用它们
    if (player.tier && player.tierMode) {
      return {
        hasTiers: true,
        allTiers: [{ tier: player.tier, mode: player.tierMode }]
      };
    }
    
    // 如果没有段位，显示无等级
    return {
      hasTiers: false,
      allTiers: []
    };
  }
  
  const tierDisplay = getTierDisplay();

  return (
    <>
      <div
        className="grid grid-cols-12 gap-2 md:gap-4 px-2 md:px-4 py-3 bg-[#1e2228] rounded-lg items-center hover:bg-[#23272e] transition-all duration-200 cursor-pointer hover-scale hover:shadow-md"
        onClick={() => setIsModalOpen(true)}
      >
        <div className="col-span-1">
          <div className={`font-bold text-base md:text-lg ${rankColor}`}>{player.rank || '-'}.</div>
        </div>

        <div className="col-span-5 md:col-span-4">
          <div className="flex items-center gap-1 md:gap-3">
            <div className="relative">
              <img 
                src={player.avatar || "/placeholder-user.jpg"} 
                alt={player.name} 
                className="w-8 h-8 md:w-10 md:h-10 rounded-full object-cover border-2 border-gray-700 hover:border-gray-500 transition-colors" 
                onError={(e) => {
                  e.currentTarget.src = "/placeholder-user.jpg"; 
                  e.currentTarget.onerror = null;
                }}
              />
              {player.rank && player.rank <= 3 && (
                <div className="absolute -top-1 -right-1 animate-pulse">
                  <Trophy className="w-3 h-3 md:w-4 md:h-4 text-yellow-500" />
                </div>
              )}
            </div>
            <div className="min-w-0">
              <div className="font-medium text-sm md:text-base truncate">{player.name}</div>
              <TooltipProvider>
                <Tooltip>
                  <TooltipTrigger asChild>
                    <div className="text-xs md:text-sm flex items-center cursor-help truncate" style={{ color: player.title?.color || "#808080" }}>
                      {player.title?.icon && (
                        <img 
                          src={player.title.icon} 
                          alt="称号图标" 
                          className="w-3 h-3 md:w-4 md:h-4 mr-1 object-contain" 
                        />
                      )}
                      <span className="truncate">{player.title?.name || "新手"}</span>
                      <span className="ml-1 truncate hidden sm:inline">({player.title?.points || 0} points)</span>
                    </div>
                  </TooltipTrigger>
                  <TooltipContent className="bg-gray-800 text-white border-gray-700 rounded-md p-2 animate-fade-in shadow-lg">
                    <p className="font-medium">{player.title?.name || "新手"}</p>
                    <p className="text-sm mt-1">{player.title?.description || "玩家称号"}</p>
                    <p className="text-xs text-gray-400 mt-1">得分: {player.title?.points || 0}</p>
                  </TooltipContent>
                </Tooltip>
              </TooltipProvider>
            </div>
          </div>
        </div>

        <div className="col-span-2 md:col-span-3 flex justify-center md:justify-start">
          <div className={`inline-block px-1 md:px-2 py-0.5 md:py-1 rounded text-xs md:text-sm font-medium ${getRegionColor(player.region || "未设置")} transition-colors hover-brightness`}>
            {getRegionName(player.region) || "未设置"}
          </div>
        </div>

        <div className="col-span-4">
          <div className="flex flex-wrap items-center gap-1 md:gap-1.5 max-w-full">
            {tierDisplay.hasTiers ? (
              <>
                {tierDisplay.allTiers.map((tierInfo, index) => (
                  <div key={index} className="flex items-center gap-1 bg-gray-800/50 rounded px-1 py-0.5 mb-1 transition-colors hover:bg-gray-700/50">
                    {getModeIcon(tierInfo.mode)}
                    <span 
                      className={`text-xs font-medium ${getTierClassName(tierInfo.tier)} rounded px-1`}
                    >
                      {tierInfo.tier}
                    </span>
                  </div>
                ))}
              </>
            ) : (
              <span className="text-xs md:text-sm text-gray-400">无等级</span>
            )}
          </div>
        </div>
      </div>

      <PlayerModal player={player} isOpen={isModalOpen} onClose={() => setIsModalOpen(false)} />
    </>
  )
}

function getRankColor(rank: number): string {
  if (rank === 1) return "text-yellow-400"
  if (rank === 2) return "text-gray-300"
  if (rank === 3) return "text-amber-600"
  return "text-gray-200"
}

function getRegionName(region: string | undefined): string {
  if (!region) return "未设置";
  
  // 如果地区字符串包含分隔符"|"，说明需要解析
  if (region.includes('|')) {
    const parts = region.split('|');
    return parts[0]; // 返回地区名称部分
  }
  
  return region;
}

function getRegionColor(region: string): string {
  // 默认颜色
  let bgColor = "bg-blue-900/50";
  let textColor = "text-blue-200";
  
  // 如果地区字符串包含分隔符"|"，解析出颜色代码
  if (region && region.includes('|')) {
    const parts = region.split('|');
    const regionName = parts[0];
    const regionColor = parts[2];
    
    if (regionColor) {
      // 从十六进制颜色代码构建CSS类
      // 使用内联样式而不是CSS类，因为动态生成的CSS类不支持
      return "bg-gray-900/50 text-gray-200"; // 使用默认颜色作为备选
    }
    
    // 如果是预定义地区，使用预定义颜色
    switch (regionName) {
      case "中国":
        return "bg-red-900/50 text-red-200";
      case "亚洲":
        return "bg-yellow-900/50 text-yellow-200";
      case "欧洲":
        return "bg-blue-900/50 text-blue-200";
      case "北美":
        return "bg-green-900/50 text-green-200";
      case "南美":
        return "bg-purple-900/50 text-purple-200";
      case "大洋洲":
        return "bg-indigo-900/50 text-indigo-200";
      case "非洲":
        return "bg-orange-900/50 text-orange-200";
    }
  }
  
  // 预定义地区名称的颜色
  switch (region) {
    case "中国":
      return "bg-red-900/50 text-red-200";
    case "亚洲":
      return "bg-yellow-900/50 text-yellow-200";
    case "欧洲":
      return "bg-blue-900/50 text-blue-200";
    case "北美":
      return "bg-green-900/50 text-green-200";
    case "南美":
      return "bg-purple-900/50 text-purple-200";
    case "大洋洲":
      return "bg-indigo-900/50 text-indigo-200";
    case "非洲":
      return "bg-orange-900/50 text-orange-200";
    default:
      return "bg-blue-900/50 text-blue-200";
  }
}

function getTierClassName(tier: string): string {
  switch (tier) {
    case "HT1":
      return "text-yellow-200"
    case "LT1":
      return "text-yellow-200"
    case "HT2":
      return "text-gray-200"
    case "LT2":
      return "text-gray-200"
    case "HT3":
      return "text-amber-200"
    case "LT3":
      return "text-amber-200"
    case "HT4":
      return "text-blue-200"
    case "LT4":
      return "text-blue-200"
    case "HT5":
      return "text-emerald-200"
    case "LT5":
      return "text-emerald-200"
    default:
      return "text-gray-200"
  }
}

